/*
 * @Description: 档案导出管理reducer
 * @Author: Rfan
 * @Date: 2022-06-21 21:37:30
 * @LastEditTime: 2022-06-23 18:25:31
 */

import { jsonClone } from '@/utils';
import { delItemByIdArray, updateItemById } from '@/utils/list';
import {
  SET_EXPORT_LIST,
  DELETE_EXPORT_ITEM,
  SET_SELECTED_ITEM,
  SET_SELECT_EXPORT_TYPE,
  DELETE_EXPORT_ORIGIN,
  SET_EXPORT_ITEM_PROCESS,
  EDIT_EXPORT_LIST
} from '../constants';
import { SET_BATCH_ITEM_PROCESS } from '@/view/accession/BatchManage/constants';

export const ExportMgtReducer = (state, action) => {
  switch (action.type) {
    /**
     * @description: 设置选中的导出单类型
     */
    case SET_SELECT_EXPORT_TYPE:
      return {
        ...state,
        selectExportType: action.data
      };

    /**
     * @description: 保存表格选中的条目id
     * @param {number[]} data
     */
    case SET_SELECTED_ITEM:
      return { ...state, selectItems: action.data };

    /**
     * @description: 设置导出单列表
     * @param {Array} data 导出单列表
     */
    case SET_EXPORT_LIST: {
      return {
        ...state,
        exportList: action.data
      };
    }

    /**
     * @description: 设置导出单列表
     * @param {Array} data 导出单列表
     */
    case EDIT_EXPORT_LIST: {
      return {
        ...state,
        exportList: updateItemById(action.id, action.data, state.exportList)
      };
    }

    /**
     * @description: 删除导出单条目原文
     * @param {number[]} ids 删除的ID列表
     */
    case DELETE_EXPORT_ORIGIN: {
      const exportList = jsonClone(state.exportList);
      if (action.ids instanceof Array) {
        exportList.forEach((item) => {
          if (action.ids.indexOf(item.id) < 0) {
            item.exportInfo.deleted = 1;
          }
        });
      } else {
        exportList.forEach((item) => {
          if (item.id === action.ids) {
            item.exportInfo.deleted = 1;
          }
        });
      }
      return {
        ...state,
        exportList
      };
    }

    /**
     * @description: 设置列表进度
     * @param {*} data websocket消息
     * @param {*} item 修改的条目
     * @return {*}
     */
    case SET_EXPORT_ITEM_PROCESS: {
      const { data, item } = action;
      const { progress, message, status } = data;
      item.progress = progress;
      item.message = message;
      if (progress === 100) {
        item.status = status;
      }
      return {
        ...state,
        batchList: updateItemById(item.id, item, state.exportList)
      };
    }

    /**
     * @description: 删除导出单
     * @param {number[]} ids 删除的ID列表
     */
    case DELETE_EXPORT_ITEM: {
      return {
        ...state,
        exportList: delItemByIdArray(action.ids, state.exportList)
      };
    }

    default:
      console.log('untouched', action);
      return state;
  }
};
